package com.imoo.springcloud;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author caryguan
 * @version V1.0
 * @Package com.imoo.springcloud
 * @date 2020/10/19 16:08
 */
@RestController
@Slf4j
public class Controller {

    @Autowired //一个简易版的负载均衡client,后面写ribbon
    //当我们把eureka加载进来的时候,这个类也完成了初始化,不需要单独声明
    private LoadBalancerClient client;

    @Autowired//需要单独声明
    private RestTemplate restTemplate;

    @GetMapping("/hello")
    public String hello() {
        //从eureka服务治理中心拉取选择一个需要的service
        ServiceInstance instance = client.choose("eureka-client");

        //防御式的编程,假设所有输入不安全
        if (instance == null) {
            return "No available instances";
        }

        //不为空我们先要得到地址url,信息可以从instance获取
        String target = String.format("http://%s:%s/sayHi",
                instance.getHost(),
                instance.getPort());

        log.info("url is " + target);

        //发起服务调用
        return restTemplate.getForObject(target, String.class);
    }

    @PostMapping("/hello")
    public Friend helloPost() {
        //从eureka服务治理中心拉取选择一个需要的service
        ServiceInstance instance = client.choose("eureka-client");

        //防御式的编程,假设所有输入不安全
        if (instance == null) {
            return null;
        }

        //不为空我们先要得到地址url,信息可以从instance获取
        String target = String.format("http://%s:%s/sayHi",
                instance.getHost(),
                instance.getPort());

        log.info("url is " + target);

        Friend friend = new Friend();
        friend.setName("Eureka Consumer");
        //发起服务调用
        return restTemplate.postForObject(target, friend, Friend.class);
    }
}